import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:math' as math;
import 'package:get/get.dart';
import 'package:hixing_app/views/test_view/canvas_utils.dart';
import 'package:hixing_app/views/test_view/test_matrix4/rect_element_model.dart';

class TestOblique extends StatefulWidget {
  @override
  _TestObliqueState createState() => _TestObliqueState();
}

class _TestObliqueState extends State<TestOblique> {
  List<RectInfoModel> rectList = [];
  CanvasEventType? eventType;

  // 平移
  double dx = 100;
  double dy = 100;

  // 缩放
  double scaleX = 1;
  double scaleY = 1;

  Size imgSize = Size(100, 100);

  // 旋转
  double rotationAngle = 0.0;
  Offset initialPosition = Offset(0, 0);

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    SystemChrome.setPreferredOrientations(// 使设备横屏显示
        [DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // appBar: AppBar(
      //   title: Text('模板'),
      // ),
      body: Stack(
        children: [
          Listener(
            onPointerDown: (details) {
              // 获取点击的位置
              final RenderBox renderBox =
                  context.findRenderObject() as RenderBox;
              // 需要初始值加上默认的偏移量
              final globalPosition =
                  renderBox.localToGlobal(details.localPosition);
              initialPosition = details.localPosition;
              final offsetLocal = globalPosition - Offset(dx, dy);
              for (var element in rectList) {
                if (element.rect.contains(offsetLocal)) {
                  // 处理点击事件
                  print('Element clicked: ${element.type}');
                  eventType = element.type;
                  break;
                }
              }
            },
            onPointerUp: (_) {
              eventType = null;
            },
            onPointerMove: (details) {
              final newPosition = details.localPosition;
              final delta = newPosition - initialPosition;
              if (eventType == CanvasEventType.rotate) {
                final angle = math.atan2(delta.dy, delta.dx);

                print("angle:${angle}");
                final distance = delta.distance;
                if (initialPosition != null) {
                  setState(() {
                    // imgSize.width = distance;
                    // imgSize.height = distance;

                    rotationAngle = angle;
                  });
                }
              }
            },
            child: CustomPaint(
              size: Size.infinite,
              painter: MyCustomPainter(
                  rotationAngle: rotationAngle,
                  scaleX: scaleX,
                  scaleY: scaleY,
                  imgSize: imgSize,
                  rectList: rectList,
                  dx: dx,
                  dy: dy),
            ),
          ),
          Positioned(
              top: 30,
              left: 30,
              child: Container(
                decoration: BoxDecoration(
                    color: Colors.black26,
                    borderRadius: BorderRadius.circular(40)),
                child: IconButton(
                  onPressed: () {
                    Get.back();
                  },
                  icon: Icon(
                    Icons.arrow_back,
                    color: Colors.yellowAccent,
                    size: 30,
                  ),
                ),
              ))
        ],
      ),
    );
  }
}

class MyCustomPainter extends CustomPainter {
  MyCustomPainter(
      {this.rectList = const [],
      required this.dx,
      required this.dy,
      required this.scaleX,
      required this.scaleY,
      required this.imgSize,
      required this.rotationAngle});

  List<RectInfoModel> rectList;

  final double dx;
  final double dy;
  final double rotationAngle;
  final double scaleX;
  final double scaleY;
  final Size imgSize;

  @override
  void paint(Canvas canvas, Size size) {
    rectList.clear();
    // TODO: implement paint
    // print("size：${size}");
    Paint _paint = Paint();
    CanvasUtils.drawGrid(canvas, _paint, size);
    CanvasUtils.drawCoor(canvas, _paint, size);
    canvas.translate(dx, dy);
    canvas.save();
    Matrix4 MartrixA = Matrix4(
        0, -2, 0, 0.003, 2, 0, 0, 0.003, 0, 0, 1, 0.003, 100, -100, 0, 1);
    // Matrix4 translationMatrix = Matrix4.translationValues(dx, dy, 0);
    // Matrix4 translationMatrix = Matrix4.translationValues(dx, dy, 0);

    Rect boxRect = Rect.fromLTRB(0, 0, imgSize.width, imgSize.height);
    // 把矩形的中心点找出来
    final rectCenter = boxRect.center;
    canvas.translate(rectCenter.dx, rectCenter.dy);
    canvas.rotate(rotationAngle);
    canvas.translate(-rectCenter.dx, -rectCenter.dy);
    final renderCenterRect = Rect.fromCenter(
        center: rectCenter, width: boxRect.width, height: boxRect.height);
    canvas.drawRect(renderCenterRect, _paint..color = Colors.red);
    rectList.add(
        RectInfoModel(rect: renderCenterRect, type: CanvasEventType.image));
    canvas.restore();
    canvas.save();
    // canvas.translate(boxRect.width / 2, boxRect.height / 2);
    Rect tapRect = Rect.fromLTRB(dx, dy, dx + 30, dy + 30);
    canvas.drawRect(
        tapRect,
        _paint
          ..color = Colors.pink
          ..style = PaintingStyle.fill);
    rectList.add(RectInfoModel(rect: tapRect, type: CanvasEventType.rotate));

    canvas.restore();
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    // TODO: implement shouldRepaint
    return true;
  }
}
//
// List<Offset> getRotateVertices(
//   List<Offset> rectVertices,
//   Offset rectCenter,
//   double rotationAngle,
// ) {
//   final rotationMatrix = Matrix4.rotationZ(rotationAngle); // 构造旋转矩阵
// // 计算矩形旋转后的四个顶点的偏移量
//
//   //
//   // final rotatedRectVertices = rectVertices.map((vertex) {
//   //   final offset = vertex - rectCenter; // 计算相对于中心点的偏移量
//   //   final rotatedX = offset.dx * cosAngle - offset.dy * sinAngle; // 应用旋转矩阵
//   //   final rotatedY = offset.dx * sinAngle + offset.dy * cosAngle;
//   //   return Offset(rotatedX + rectCenter.dx, rotatedY + rectCenter.dy); // 计算旋转后的顶点位置
//   // }).toList();
// }
